<template>
  <!-- AddAuthor 组件 -->
<!--  <AddAuthor  @author-added="handleAuthorAdded" />-->
  <el-button type="primary" @click="handleAddData">添加数据</el-button>
<!--添加一个用于筛选的数据框-->
  <el-form :inline="true" :model="filterForm" >
    <el-form-item label="查询时间段">
      <el-date-picker
          v-model="filterForm.start_date"
          type="datetime"
          placeholder="选择开始日期"

      />
      <el-date-picker
          v-model="filterForm.end_date"
          type="datetime"
          placeholder="选择结束日期"

      />
      <el-form-item label="教研室" >
        <el-select
            filterable
            allow-create
            v-model="filterForm.department"
            style="width: 150px;">
          <el-option :key="'数智教研室'" :label="'数智教研室'" :value="'数智教研室'"/>
          <el-option :key="'计算机教研室'" :label="'计算机教研室'" :value="'计算机教研室'"/>
          <el-option :key="'通号教研室'" :label="'通号教研室'" :value="'通号教研室'"/>
          <el-option :key="'智能信息教研室'" :label="'智能信息教研室'" :value="'智能信息教研室'"/>
          <el-option :key="'非教研室人员'" :label="'非教研室人员'" :value="'非教研室人员'"/>
        </el-select>
      </el-form-item>
<!--      显示可以选择的人名 加宽-->
      <el-form-item label="人名/账号" >
        <el-select
            filterable
            allow-create
            v-model="filterForm.username"
            style="width: 150px;">
          <el-option v-for="item in author_list"
                     :key="item.username"
                     :label="`${item.name} (${item.username})`"
                     :value="item.username">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" >
        <el-select
            filterable
            allow-create
            v-model="filterForm.revstatus"
            style="width: 150px;">
          <el-option :key="'未审核'" :label="'未审核'" :value="'未审核'"/>
          <el-option :key="'审核未通过'" :label="'审核未通过'" :value="'审核未通过'"/>
          <el-option :key="'审核通过'" :label="'审核通过'" :value="'审核通过'"/>
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="handleFilter">刷新</el-button>
    </el-form-item>

  </el-form>
  <el-table :data="tableData.value" border type="index" style="width: 100%" v-loading="table_loading">
    <el-table-column
        v-for="(value, key) in get_reportInfo"
        :key="key"
        :prop="key"
        :label="value.verbose_name"
        :width="120"
    ></el-table-column>
    <!-- 附件列保持不变，但假设添加了一个attachmentText字段用于显示附件名 -->
    <el-table-column prop="attachment" label="附件" width="250" >
      <template #default="scope">
        <a :href="scope.row.attachment" target="_blank">{{ scope.row.attachmentText || '附件' }}</a>
        <el-button size="small" type="primary" @click="handleFileUpload(scope.row)" :loading="attachment_loading[scope.row.id]">{{  attachment_loading[scope.row.id]? '上传中' : '点击上传' }}</el-button>
        <input
          type="file"
          style="display: none;"
          @change="onFileSelected"
          :ref="el => { if (el) fileInputs[scope.row.id] = el; }"
        />
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="200"> <!-- "Operations"改为中文"操作" -->
      <template #default="scope">
        <el-button  type="primary" size="small" @click="handleClickDelete(scope.row)" :loading="delete_loading">删除</el-button>
        <el-button  type="primary" size="small" @click="handleClickEdit(scope.row)" :loading="edit_loading">编辑</el-button>
        <br></br>
        <el-button  type="primary" size="small" @click="handleClickApproveOK(scope.row)" :loading="approveY_loading">审核通过</el-button>
        <el-button  type="primary" size="small" @click="handleClickApproveNO(scope.row)" :loading="approveN_loading">审核不通过</el-button>
      </template>
    </el-table-column>
  </el-table>


  <div class="pagination-container">
  <el-pagination
        v-model:currentPage="filterForm.page"
        :page-size="10"
        layout="prev, pager, next"
        :total="total_datas "
        @current-change="handleCurrentChange"
    />
    </div>
  <AddData  :tableType="tableType" :isAdmin="true" @refresh-table="handleSucceedAdd"/>
  <EditData :tableType="tableType" :isAdmin="true" @refresh-table="handleSucceedEdit"/>
</template>

<script setup>
import {ref, onMounted, watchEffect, onBeforeUnmount, reactive, watch, computed} from 'vue';
import setting from '@/setting.js';
import eventBus from "@/event-bus.js";
import {ElMessage,ElMessageBox} from "element-plus";
import AddData from "@/components/Main/ReportManagement/AddData.vue";
import EditData from "@/components/Main/ReportManagement/EditData.vue";
import global, {formDataApi, jsonApi} from "@/global.js";

const props = defineProps({
  tableType: {
    type: String,
    required: true
  }
});
const filterForm = reactive({
  start_date: '',
  end_date: '',
  page: 1,
  username: '',
  department: '',
  revstatus:''
});
// State
const accessToken = ref(localStorage.getItem('access_token'));
const refreshToken = ref(localStorage.getItem('refresh_token'));
const originalAuthorList = ref(JSON.parse(localStorage.getItem('alluser')) || []);
// 创建一个响应式的 author_list，初始化为原始作者列表的副本
const author_list = ref([...originalAuthorList.value]);
const reportInfo = ref({});
const get_reportInfo = ref({});
const tableData = reactive([]);
let orgTableData = null;//原始数据，其中的json没有经过json.parse
const storedReportInfo = localStorage.getItem('reportinfo');
const fileInputs = reactive({});
let currentRow = ref(null);
let total_datas = ref(0);
//loading
const table_loading=ref(false);
const attachment_loading=ref(null);
const delete_loading = ref(false);
const edit_loading = ref(false);
const approveY_loading = ref(false);
const approveN_loading = ref(false);
const initializeLoadingState = () => {
      const loadingState = {};
      tableData.value.forEach(row => {
        loadingState[row.id] = false;
      });
      attachment_loading.value = loadingState;
    };
onMounted(() => {
  //开启接收事件监听
  eventBus.on('update-report-form-table-type', handleTableTypeUpdate);
  // 开启一个初始化
  author_list.value.unshift({username:'000',name:'所有人'});
// 设置结束日期为今天
  const now = new Date();
// 获取本地时区的年、月、日、时、分、秒
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并且补零
  const date = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

 // 拼接成 "yyyy-MM-dd HH:mm:ss" 格式
  filterForm.end_date = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
 // 设置开始日期为六个月前
  // 判断当前日期属于哪个学期，并设置起始日期
   let start_date;
   if (now.getMonth() >= 7) { // 当前时间是8月到12月之间，开学时间应为8月1日
       start_date = new Date(now.getFullYear(), 7, 1); // 设置时间为8月1日
   } else if (now.getMonth() < 2) { // 当前时间是1月到1月，开学时间应为去年8月1日
       start_date = new Date(now.getFullYear() - 1, 7, 1); // 设置时间为去年8月1日
   } else { // 当前时间是2月到7月之间，开学时间应为2月1日
       start_date = new Date(now.getFullYear(), 1, 1); // 设置时间为2月1日
   }
      // 手动格式化日期为 "YYYY-MM-DD" 格式
   function formatDate(date) {
     const year = date.getFullYear();
     const month = String(date.getMonth() + 1).padStart(2, '0');
     const day = String(date.getDate()).padStart(2, '0');
     return `${year}-${month}-${day}`;
   }

   // 设置filterForm.start_date为计算出的学期开始日期
   filterForm.start_date = formatDate(start_date);
});

onBeforeUnmount(() => {
  //关闭事件监听
  eventBus.off('update-report-form-table-type', handleTableTypeUpdate);
});
const handleTableTypeUpdate = (type) => {
  if (type) {
    // 当接收到新的tableType时，进行数据加载等操作
    console.log('Received tableType:', type);
    // 这里调用getData等函数来处理新类型的数据加载
  }
};
// Methods
const handleAddData = () => {
  eventBus.emit('report-form-table-add', {
  })
};
const handleSucceedAdd=()=>{
  ElMessage({
    message: '添加成功',
    type: 'success',
  });
  refreshTable();
};
const handleSucceedEdit=()=>{
  ElMessage({
    message: '编辑成功',
    type: 'success',
  });
  refreshTable();
};
//获取数据与筛选
const handleFilter = () => {
  // 获取类别
  getDataWithAccessToken(props.tableType);
};
const handleCurrentChange = (currentPage) => {
  // 更新当前页码
  filterForm.page = currentPage;
  // 重新加载数据
  getDataWithAccessToken(props.tableType);
};
// 字段筛选
const getReportInfo = async () => {
  reportInfo.value = JSON.parse(storedReportInfo)[props.tableType];
  //获取时需要排除的字段
  get_reportInfo.value = reportInfo.value;
  const get_excludeFields = ['model_name', 'attachment'];
  // 使用 forEach 循环来遍历对象的所有键
  get_excludeFields.forEach(field => {
      // 如果报告信息中存在要排除的字段，则删除它
      if (get_reportInfo.value.hasOwnProperty(field)) {
        delete get_reportInfo.value[field];
      }
    });
}


// 当选择部门编号时，更新 author_list

// 监听 filterForm.department 的变化
watch(
  () => filterForm.department,
  (newDepartment) => {
    if (!newDepartment) {
      // 如果没有选择部门，则恢复原始作者列表
      author_list.value = [...originalAuthorList.value];
    } else {
      // 否则，更新 author_list 为仅包含所选部门的用户
      author_list.value = originalAuthorList.value.filter(user => user.department === newDepartment);
    }
    author_list.value.unshift({username:'000',name:'所有人'});
  },
  { immediate: true } // 立即执行一次以确保初始状态正确
);
// 获取数据
const getDataWithAccessToken = async (property) => {
  const requestBody = {
    Report: property,
    start_time: filterForm.start_date,
    end_time: filterForm.end_date,
    page: filterForm.page,
    username: filterForm.username,
    department: filterForm.department,
    revstatus:filterForm.revstatus
  };

  try {
    table_loading.value = true;
    const response = await jsonApi('/reportmanager/getforadmin/',JSON.stringify(requestBody));
    let orgdata = await response.json();
    const data = orgdata['datas'];
    total_datas = orgdata['total_datas'];
    orgTableData = JSON.parse(JSON.stringify(data));
    if (!response.ok) {
        showError('获取数据失败', data.error, 2000);
    } else {
      for(let i=0;i<data.length;i++){
         if(data[i].authors){
           let newauthos=""
           for(let j=0;j<data[i].authors.length;j++){
             let author=data[i].authors[j]
             newauthos+=`${author.name}_${ author.role }_(${author.account})||`;
           }
           data[i].authors=newauthos
         }
         if(data[i].score){
           let newscore=""
           for(let j=0;j<data[i].score.length;j++){
             let one_score=data[i].score[j]
             newscore+=`(_账号：${one_score.account}_分数：${one_score.author_score}_)，`;
           }
           data[i].score=newscore
         }
      }
      tableData.value = data; // 假设返回的数据直接用于表格
      console.log(tableData.value);
      table_loading.value = false;
      initializeLoadingState();

    }
  } catch (error) {
    console.error(error);
    table_loading.value = false;
  }
};




//删除相关
const handleDelete = async (row) => {
  try {
    // 使用Element Plus的ElMessageBox确认对话框
    const result = await ElMessageBox.confirm(
      '此操作将永久删除该数据, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    if (result === 'confirm') {
      // 用户点击了确认按钮，执行删除操作
      await handleClickDelete(row);
    }
  } catch (error) {
    console.error('删除操作中发生错误:', error);
  }
};
//删除表格数据
const handleClickDelete = async (row) => {

    try {
      delete_loading.value = true;
      const requestBody = { "id": row.id, "Report": props.tableType};
      const accessToken = localStorage.getItem('access_token')
      const refreshToken = localStorage.getItem('refresh_token');

      const response = await jsonApi('/reportmanager/deleteforadmin/',JSON.stringify(requestBody));
      const data = await response.json();

      if (data.code === 'token_not_valid') {
        if (await global.refreshAndRetry()) {
          await handleClickDelete(); // 假设handleSubmitAdd是你的提交函数
        }
      } else if (!response.ok) {
        ElMessage({
          type: 'error',
          message: data.error || '删除失败'
        });
      } else {
        await refreshTable();
        ElMessage({
          type: 'success',
          message: '删除成功!'
        });
      }
      delete_loading.value = false;
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '网络错误，请重试'
      });
      delete_loading.value = false;

    }
  }

//修改表格数据相关
const handleClickEdit= async (row) => {
  let data;
  // 返回orgTableData中的id==row.id的数据
  data=orgTableData.find(item => item.id === row.id);
      //修改当前表格行的数据，将会弹出一个上文的<el-dialog>，这个表单具有当前行的数据
      eventBus.emit('report-form-table-edit', {
        EditData:data,
        ID:row.id,
  })
}

//审核
const handleClickApproveOK= async (row) => {
  /*
  * {
    "Report": "TeacherCompetition",
    "id":4,
    "revstatus":"审核通过"
}
* /reportmanager/approval/
*
* */
  try {
    approveY_loading.value = true;
    const requestBody = { "Report": props.tableType, "id": row.id, "revstatus": "审核通过" };
    const response = await jsonApi('/reportmanager/approval/',JSON.stringify(requestBody));
    const data = await response.json();
    if (data.code === 'token_not_valid') {
      if (await global.refreshAndRetry()) {
        await handleClickApproveOK(); // 假设你的提交函数
      }
    } else if (response.ok) {
      ElMessage({
        type: 'success',
        message: '成功审核!'
      });
      await refreshTable();
    } else {

      ElMessage({
        type: 'error',
        message: data.error || '审核失败'
      });
    }
    approveY_loading.value = false;
  }catch (error) {
    ElMessage({
      type: 'error',
      message: '网络错误，请重试'
    })
    approveY_loading.value = false;
  }
}
//不审核
const handleClickApproveNO= async (row) => {
  /*
    * {
      "Report": "TeacherCompetition",
      "id":4,
      "revstatus":"审核通过"
  }
  * /reportmanager/approval/
  *
  * */
  try {
    approveN_loading.value = true;
    const requestBody = { "Report": props.tableType, "id": row.id, "revstatus": "审核未通过" };
    const response = await jsonApi('/reportmanager/approval/',JSON.stringify(requestBody));
    const data = await response.json();
    if (data.code === 'token_not_valid') {
      if (await global.refreshAndRetry()) {
        await handleClickApproveOK(); // 假设你的提交函数
      }
    } else if (!response.ok) {
      ElMessage({
        type: 'error',
        message: data.error || '审核失败'
      });
    } else {
      await refreshTable();
      ElMessage({
        type: 'success',
        message: '已取消审核!'
      });
    }
    approveN_loading.value = false;
  }catch (error) {
    ElMessage({
      type: 'error',
      message: '网络错误，请重试'
    })
    approveN_loading.value = false;
  }

}



// 上传相关
const handleFileUpload = async (row) => {

  fileInputs[row.id]?.click();
  // 你可能需要在这里以某种方式将当前行数据传递给文件上传处理函数
  // 例如，可以将 row 保存在一个组件的数据属性中，以便稍后在文件选择后使用
  currentRow = row;
};
const onFileSelected = async (event) => {
  const file = event.target.files[0];
  if (file) {
    //检查file是不是pdf或者zip
    if (file.type === 'application/pdf' || file.type === 'application/x-zip-compressed' || file.type === 'image/jpeg' || file.type === 'image/png') {
      // 显示上传进度
      // 在这里处理文件上传逻辑
      await uploadFile(currentRow, file);
    } else {
      // 显示错误消息
      ElMessage.error('请选择JPG图片、JPGE图片、PNG图片、PDF、ZIP文件');
    }



  }
};
//  上传文件
const uploadFile = async (row, file) => {
  // 创建 FormData 对象，并添加文件和其他可能需要的数据
  const formData = new FormData();
  const accessToken = localStorage.getItem('access_token');
  const refreshToken = localStorage.getItem('refresh_token');
  formData.append('file', file);
  formData.append('id', row.id); // 假设每一行数据有一个唯一的 id
  formData.append('Report', props.tableType); // 假设每一行数据有一个唯一的 id
  // 使用 Axios、Fetch API 或 XMLHttpRequest 发送文件到服务器
  try {
    attachment_loading.value[row.id]=true;
    const response = await formDataApi('/reportmanager/uploadforadmin/', formData)
    const data = await response.json();
    console.log(data);
    if (!response.ok) {

        ElMessage({
          type: 'error',
          message: data.error
        });
      throw new Error(`HTTP error! data: ${data}`);

    } else {
      ElMessage({
        type: 'success',
        message: '上传成功!'
      });
      await refreshTable();
      console.log('File uploaded successfully', data);

    }
   attachment_loading.value[row.id]=false;


  } catch (error) {
    console.error('File upload failed', error);
    attachment_loading.value[row.id]=false;
  }
};
//刷新表格获取新数据
const refreshTable = async () => {
  // 获取新的数据
  filterForm.end_date = new Date(Date.now() + 86400000).toISOString();
  await getDataWithAccessToken(props.tableType);
};



watchEffect(async () => {
  if (!props.tableType) return; // 确保 tableType 存在再执行后续逻辑
  console.log(props.tableType);
  if (storedReportInfo && props.tableType) {
    await getReportInfo();
    await getDataWithAccessToken(props.tableType);
  }
});


function showError(message, error, duration) {
  console.error(message, error);
  // 实现错误展示逻辑，例如使用通知组件
}
</script>

<style>
.pagination-container {
  display: flex; /* 使用 flexbox 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中，如果需要的话 */
  margin-top: 20px; /* 可选，添加一些顶部边距 */
}
</style>
